package com.mopon.saas.server.thrift;

import java.lang.reflect.Constructor;

import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.THsHaServer;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TTransportException;

public class ThriftServerProxy {

	private int serverPort;
	private String serviceInterface;
	private Object serviceImplObject;

	public int getServerPort() {
		return this.serverPort;
	}

	public void setServerPort(int serverPort) {
		this.serverPort = serverPort;
	}

	public String getServiceInterface() {
		return this.serviceInterface;
	}

	public void setServiceInterface(String serviceInterface) {
		this.serviceInterface = serviceInterface;
	}

	public Object getServiceImplObject() {
		return this.serviceImplObject;
	}

	public void setServiceImplObject(Object serviceImplObject) {
		this.serviceImplObject = serviceImplObject;
	}

	public void start() {
		new Thread() {
			public void run() {
				try {
					System.out.println("thrift server is starting... on port:" + ThriftServerProxy.this.getServerPort());
					Class<?> Processor = Class.forName(ThriftServerProxy.this.getServiceInterface() + "$Processor");
					Class<?> Iface = Class.forName(ThriftServerProxy.this.getServiceInterface() + "$Iface");

					Constructor<?> constructor = Processor.getConstructor(new Class[] { Iface });

					TProcessor tprocessor = (TProcessor) constructor.newInstance(new Object[] { ThriftServerProxy.this
									.getServiceImplObject() });
					TNonblockingServerSocket tnbSocketTransport = new TNonblockingServerSocket(ThriftServerProxy.this.getServerPort());

					THsHaServer.Args tnbArgs = new THsHaServer.Args(tnbSocketTransport);
					tnbArgs.processor(tprocessor);
					tnbArgs.transportFactory(new TFramedTransport.Factory());
					tnbArgs.protocolFactory(new TBinaryProtocol.Factory());

					TServer server = new TNonblockingServer(tnbArgs);
					server.serve();

					System.out.println("thrift server is started");
				} catch (TTransportException e) {
					System.out.println(e.getMessage());
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
			}
		}.start();
	}

	public void startServer() {
		this.setServerPort(8089);
		this.setServiceInterface("com.mopon.saas.common.thrift.ThriftService");
		this.setServiceImplObject(new ThriftBaseServiceImpl());
		start();
	}
	
	public static void main(String[] args) {
		ThriftServerProxy proxy = new ThriftServerProxy();
		proxy.startServer();
	}
}
